from django.shortcuts import render
from rest_framework import status
from rest_framework.views import APIView
from rest_framework.permissions import AllowAny
from rest_framework.response import Response
from rest_framework.viewsets import GenericViewSet
from rest_framework.decorators import action
from rest_framework.mixins import ListModelMixin
from .models import Service, Banner, Category, Technician
from .serializers import BannerSerializer, CategorySerializer, TechnicianSerializer, ServiceSerializer
from rest_framework.parsers import MultiPartParser, FormParser
from decimal import Decimal

class BannerViewSet(ListModelMixin, GenericViewSet):
    """轮播图视图集"""
    permission_classes = [AllowAny]
    queryset = Banner.objects.filter(is_active=True)
    serializer_class = BannerSerializer
    parser_classes = (MultiPartParser, FormParser)
    
    def list(self, request, *args, **kwargs):
        """获取轮播图列表"""
        banners = self.get_queryset().order_by('sort_order', '-created_at')
        serializer = self.get_serializer(banners, many=True)
        return Response(serializer.data)
    
    @action(detail=False, methods=['post'], permission_classes=[AllowAny])
    def upload_image(self, request):
        """上传轮播图图片"""
        try:
            from common.utils import upload_to_minio
            image_file = request.FILES.get('image')
            if image_file:
                # 上传到MinIO
                image_url = upload_to_minio(
                    image_file, 
                    0,  # 系统图片，用户ID为0
                    'banners'
                )
                
                return Response({'url': image_url}, status=status.HTTP_201_CREATED)
            else:
                return Response({'error': '未提供图片文件'}, status=status.HTTP_400_BAD_REQUEST)
        except Exception as e:
            return Response({'error': f'上传失败: {str(e)}'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


class ImageViewSet(GenericViewSet):
    """图片资源视图集"""
    permission_classes = [AllowAny]
    
    @action(detail=False, methods=['get'], permission_classes=[AllowAny])
    def app_images(self, request):
        """获取应用程序所需的所有图片资源"""
        # 从数据库获取轮播图
        banners = Banner.objects.filter(is_active=True).order_by('sort_order', '-created_at')
        banner_data = []
        for banner in banners:
            banner_data.append({
                "id": banner.id,
                "image": banner.image,
                "title": banner.title,
                "description": banner.description
            })
        
        # 从数据库获取服务分类
        categories = Category.objects.filter(is_active=True).order_by('sort_order')
        category_data = []
        for category in categories:
            category_data.append({
                "id": category.name,
                "name": category.get_name_display(),
                "icon": category.icon
            })
        
        # 从数据库获取技师
        technicians = Technician.objects.filter(is_active=True)
        technician_data = []
        for technician in technicians:
            technician_data.append({
                "id": technician.id,
                "name": technician.name,
                "avatar": technician.avatar,
                "rating": float(technician.rating),
                "order_count": technician.order_count
            })
        
        # 获取服务项目
        services = Service.objects.filter(is_active=True)
        service_data = []
        for service in services:
            service_data.append({
                "id": service.id,
                "name": service.name,
                "image": service.image,
                "duration": service.duration,
                "price": str(service.price),
                "original_price": str(service.price * Decimal('1.2'))  # 示例：原价为现价的1.2倍
            })
        
        image_urls = {
            "banners": banner_data,
            "categories": category_data,
            "technicians": technician_data,
            "services": service_data
        }
        
        return Response(image_urls)


class TechnicianViewSet(GenericViewSet):
    """技师视图集"""
    permission_classes = [AllowAny]
    serializer_class = TechnicianSerializer
    
    @action(detail=False, methods=['get'], permission_classes=[AllowAny])
    def recommended(self, request):
        """获取推荐技师列表"""
        # 从数据库获取推荐技师
        technicians = Technician.objects.filter(is_active=True)[:3]  # 获取前3个技师
        serializer = self.get_serializer(technicians, many=True)
        return Response(serializer.data)


class ServiceViewSet(GenericViewSet):
    """服务视图集"""
    permission_classes = [AllowAny]
    serializer_class = ServiceSerializer
    
    @action(detail=False, methods=['get'], permission_classes=[AllowAny])
    def hot(self, request):
        """获取热门服务列表"""
        # 从数据库获取热门服务
        services = Service.objects.filter(is_active=True)[:2]  # 获取前2个服务
        serializer = self.get_serializer(services, many=True)
        return Response(serializer.data)